import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import Breadcrumb from "../components/Breadcrumb";
import Footer from "../components/Footer";
import Header from "../components/Header";
import Pager from "../components/Pager";
import service from "../service";
import moment from "moment";

export default function News() {
  //面包屑路径
  const path = [
    { name: "首页", href: "/" },
    { name: "公司动态", href: "/news" },
    { name: "新闻列表", href: "/news" },
  ];
  //新闻列表：newsList
  let [newsList, setNewsList] = useState([]);
  //当前分页显示的页号
  let [pageNum, setPageNum] = useState(0);
  //新闻分页显示的总页数
  let [pageCount, setPageCount] = useState(0);
  //组件挂载时
  useEffect(function () {
    loadData(1);
  }, []);
  //num就是要加载的页号
  // ①当前组件挂载完成时   ②分页条子组件点击某个特定页号
  function loadData(num) {
    // console.log("父组件正在加载指定页号数据：", num);
    service
      .newsSelect(num)
      .then((data) => {
        console.log(data);
        setPageCount(data.pageCount); //分页查询查得的总页数
        setPageNum(data.pageNum); //分页查询查得的当前页号
        setNewsList(data.data); //分页查询查得的新闻列表
      })
      .catch((err) => console.log(err));
  }
  return (
    <>
      {/* header */}
      <div className="header_box">
        <Header></Header>
      </div>
      {/* breadcrumb */}
      <Breadcrumb path={path}></Breadcrumb>
      {/* main */}
      <div className="main container">
        <div className="news">
          <ul>
            {newsList.map((n, i) => (
              <li key={n.nid}>
                <span>{moment(Number(n.pubTime)).format("YY-MM-DD")}</span>
                <Link to={`/news_details?nid=${n.nid}`}>{n.title}</Link>
              </li>
            ))}
          </ul>
        </div>
        {/* 分页导航*/}
        {/* 父组件给子组件传递数据： pageCount(总页数) 和 pageNum(当前页号) */}
        {/* 父组件给子组件传递数据： loadData(方法，用于加载指定数据) */}
        <Pager
          loadData={loadData}
          pageCount={pageCount}
          pageNum={pageNum}
        ></Pager>
      </div>
      {/* footer */}
      <footer className="footer">
        <Footer></Footer>
      </footer>
    </>
  );
}
